<script setup>
import { countRoom } from '@/api/room.js';
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';

const roomCounts = ref({
  room: 0,
  single: 0,
  twin: 0,
  large: 0
});

// 用于存储饼图实例的响应式引用
const pieChartRef = ref(null);

// 在组件挂载后获取房间数量数据并初始化饼图
onMounted(async () => {
  try {
    const response = await countRoom();
    if (response.status) {
      roomCounts.value = response.data;
      initPieChart();
    } else {
      console.error('获取房间数量数据失败，错误信息:', response.message);
    }
  } catch (error) {
    console.error('请求出现错误:', error);
  }
});

// 初始化饼图函数
const initPieChart = () => {
  const pieChart = echarts.init(pieChartRef.value);
  const totalRooms = roomCounts.value.room;
  const data = [
    { name: '单人间', value: roomCounts.value.single },
    { name: '双人间', value: roomCounts.value.twin },
    { name: '大房间', value: roomCounts.value.large }
  ];
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '房间类型占比',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  pieChart.setOption(option);
};
</script>

<template>
  <div class="room-count-wrapper">
    <div class="room-count-container">
      <h2>房间数量统计</h2>
      <div class="room-count-item">
        <span>房间总数：</span>
        <span>{{ roomCounts.room }}</span>
      </div>
      <div class="room-count-item">
        <span>单人间数量：</span>
        <span>{{ roomCounts.single }}</span>
      </div>
      <div class="room-count-item">
        <span>双人间数量：</span>
        <span>{{ roomCounts.twin }}</span>
      </div>
      <div class="room-count-item">
        <span>大房间数量：</span>
        <span>{{ roomCounts.large }}</span>
      </div>
    </div>
    <div class="room-chart-container">
      <div ref="pieChartRef" class="pie-chart"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.room-count-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  width: 800px;

  .room-count-container {
    flex: 1;
    padding: 20px;
    border-right: 1px solid #ccc;

    h2 {
      margin-bottom: 20px;
      color: #333;
    }

    .room-count-item {
      margin-bottom: 10px;
      font-size: 16px;
      color: #555;

      span:first-child {
        font-weight: bold;
      }
    }
  }

  .room-chart-container {
    flex: 1;
    padding: 20px;

    .pie-chart {
      width: 100%;
      height: 300px;
      background-color: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      border-radius: 5px;
    }
  }
}
</style>